﻿using Microsoft.Extensions.DependencyInjection;
using Quartz.Impl;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cl.Repository;
using Quartz.Spi;
using System.Reflection;
using Cl.Quartz.Jobs.Test;
using Cl.Utils.Helper;

namespace Cl.Quartz
{
    public class LimsQuartzInit
    {
        private static ServiceCollection Services { get; set; }
        private static StdSchedulerFactory? SchedulerFactory { get; set; }
        private static IScheduler? Scheduler { get; set; }

        public static void Init()
        {
            Services = new ServiceCollection();
            Services.AddScoped(typeof(CLBaseRepository<>));//加载sqlsugara仓储
            Services.AddScoped(typeof(ClRepository<>));//加载sqlsugara仓储
            Services.InjectionAllServices();//加载ioc依赖注入

            //自定义的job工厂，可以使用参数构造函数注入
            Services.AddSingleton<IJobFactory, LimsJobFactory>();
            Services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();

            #region 注册job
            // 获取当前程序集
            var assembly = Assembly.GetExecutingAssembly();
            // 注册当前程序集中所有继承自 IJob 的类
            var jobTypes = assembly.GetTypes()
                .Where(type => type.IsClass && !type.IsAbstract && typeof(IJob).IsAssignableFrom(type));
            foreach (var serviceType in jobTypes)
            {
                Services.AddSingleton(serviceType);
            }
            #endregion

            var provider = Services.BuildServiceProvider();
            var _jobFactory = provider.GetService<IJobFactory>();
            var _schedulerFactory = provider.GetService<ISchedulerFactory>();
            Scheduler = _schedulerFactory.GetScheduler().Result;
            //关键在于这里，替换掉调度器默认的任务工厂
            Scheduler.JobFactory = _jobFactory;
            Scheduler.Start();

            QuartzTest(24);
        }


        /// <summary>
        /// test方法
        /// </summary>
        /// <param name="interval">请求间隔（分钟）</param>
        public static void QuartzTest(int interval)
        {
            var _jobMap = new JobDataMap { { "FreeTime", DateTime.Now } };
            var _job = JobBuilder.Create<TestJob>().UsingJobData(_jobMap).Build();
            var _trigger = TriggerBuilder.Create().WithSimpleSchedule(s => s.WithIntervalInHours(interval).RepeatForever()).Build();
            Scheduler?.ScheduleJob(_job, _trigger);

        }

    }
}
